package hoang.hut.networkdemo.network;

import java.io.IOException;

import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
import org.apache.http.util.EntityUtils;

import android.app.ProgressDialog;
import android.content.Context;

public class AsyncHttpResponseProcess implements AsyncHttpResponseListener {

	private Context context;
	private boolean isShowDialog = true;
	private ProgressDialog progressDialog;

	public AsyncHttpResponseProcess(Context context) {
		this.context = context;
	}

	public AsyncHttpResponseProcess(Context context, boolean isShow) {
		this.context = context;
		this.isShowDialog = isShow;
	}

	@Override
	public void before() {
		if (isShowDialog) {
			if (progressDialog == null) {
				progressDialog = new ProgressDialog(context);
				progressDialog.setMessage("Waiting...");
				progressDialog.setCancelable(false);
				progressDialog.show();
			}
		}
	}

	@Override
	public void after(int statusCode, HttpResponse response) {
		if (isShowDialog) {
			if (progressDialog != null) {
				progressDialog.cancel();
				progressDialog = null;
			}
		}

		switch (statusCode) {
		case AsyncHttpBase.STATUS_NETWORK_OFF:
			Utils.showAlertPositive(context, 0, "Error",
					"Network is disconnected");
			break;

		case AsyncHttpBase.STATUS_NETWORK_ERROR:
			Utils.showAlertPositive(context, 0, "Error",
					"There is an error form server");
			break;

		case AsyncHttpBase.STATUS_NETWORK_EXCEIPTION:
			Utils.showAlertPositive(context, 0, "Error",
					"There is an error form server");
			break;

		case AsyncHttpBase.STATUS_NETWORK_TIMEOUT:
			Utils.showAlertPositive(context, 0, "Error", "Timeout...");
			break;

		case AsyncHttpBase.STATUS_NETWORK_OK:
			processHttpResponse(response);
			break;

		default:
			break;
		}

	}

	/**
	 * ham xu ly response thanh cong lay json, xu ly json
	 * 
	 * @param response
	 */
	private void processHttpResponse(HttpResponse response) {
		String jsonString = null;
		try {
			jsonString = EntityUtils.toString(response.getEntity());
			if (jsonString == null) {
				Utils.showAlertPositive(context, 0, "Error", "Server response data error");
				return;
			} else {
				processResponseSuccess(jsonString);
			}
		} catch (ParseException e) {
			e.printStackTrace();
			Utils.showAlertPositive(context, 0, "Error", e.getMessage());
		} catch (IOException e) {
			e.printStackTrace();
			Utils.showAlertPositive(context, 0, "Error", e.getMessage());
		}
		

	}

	/**
	 * phuong thuc xu ly du lieu khi thanh cong
	 * 
	 * @param json
	 */
	public void processResponseSuccess(String response) {

	}
}
